import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import app from '@/main'

import store from "./store"
import config from "./config"

axios.defaults.baseURL = config.baseUrl
axios.defaults.withCredentials = false
axios.defaults.headers['x-requested-with'] = 'XMLHttpRequest'

axios.interceptors.request.use(function(conf) {
	if (conf.url.endsWith('/oauth/token')) {
		conf.auth = {
			username: 'strive_app_id_sysplatform',
			password: 'strive_app_secret_sysplatform'
		}
	} else if (conf.url.indexOf('/admin') > -1) {
		let token = localStorage.getItem(config.tokenName)
		conf.headers['Authorization'] = `bearer ${token}`
	} else {
		conf.headers['Authorization'] = ''
	}
	return conf
}, function(err) {
	return Promise.reject(err)
});

axios.interceptors.response.use(function(response) {
	let data = response.data;
	if (data.code === '04') {
		localStorage.removeItem(config.tokenName)
		app.$router.replace({
			name: 'login'
		});
		return;
	}
	return response;
}, function(err) {
	return Promise.reject(err)
})

Vue.use(VueAxios, axios)
